<!DOCTYPE html>
<html>

<head>
  <title>WebSocket 测试客户端</title>
  <style>
    #messages {
      height: 200px;
      overflow-y: scroll;
      border: 1px solid #ccc;
      padding: 10px;
    }
  </style>
</head>

<body>
  <h1>WebSocket 测试客户端</h1>

  <div>
    <input type="text" id="urlInput" value="ws://localhost:8001" style="width: 300px;">
    <button id="connectBtn">连接</button>
    <button id="disconnectBtn" disabled>断开</button>
  </div>

  <div>
    <input type="text" id="messageInput" placeholder="输入消息">
    <button id="sendBtn" disabled>发送</button>
  </div>

  <div id="messages"></div>

  <script>
    let socket;

    document.getElementById('connectBtn').addEventListener('click', () => {
      const url = document.getElementById('urlInput').value;
      socket = new WebSocket(url);

      socket.onopen = () => {
        log('连接已建立');
        document.getElementById('connectBtn').disabled = true;
        document.getElementById('disconnectBtn').disabled = false;
        document.getElementById('sendBtn').disabled = false;
      };

      socket.onmessage = (event) => {
        log('收到: ' + event.data);
      };

      socket.onclose = () => {
        log('连接已关闭');
        document.getElementById('connectBtn').disabled = false;
        document.getElementById('disconnectBtn').disabled = true;
        document.getElementById('sendBtn').disabled = true;
      };

      socket.onerror = (error) => {
        log('错误: ' + error.message);
      };
    });

    document.getElementById('disconnectBtn').addEventListener('click', () => {
      if (socket) {
        socket.close();
      }
    });

    document.getElementById('sendBtn').addEventListener('click', () => {
      const message = document.getElementById('messageInput').value;
      if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(message);
        log('发送: ' + message);
        document.getElementById('messageInput').value = '';
      }
    });

    function log(message) {
      const messagesDiv = document.getElementById('messages');
      messagesDiv.innerHTML += `<div>${new Date().toLocaleTimeString()}: ${message}</div>`;
      messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }
  </script>
</body>

</html>